<?php
/**
 * Created by PhpStorm.
 * User: Sojo
 * Date: 2017/5/31
 * Time: 17:36
 */
namespace App\Api\Service\Product\Controllers;

use App\Eloquent\Ygt\CategoryFields;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\SellerCompany;
use App\Eloquent\Ygt\Stock;
use App\Engine\Plate;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\Category;
use App\Engine\Func;
use App\Engine\KmPrinter;
use App\Engine\Product as EngineProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\DepartmentUser;
use Illuminate\Support\Facades\Log;
use \App\Eloquent\Ygt\MaterialRetreatLog;

class ProductController extends Controller
{
    public $userId      = 25;
    public function getProductList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId              = $userInfo->company_id;
        //传参
        $page                   = request('page', 1);
        $categoryIdStr          = request('category_id',0);//多个逗号隔开!!!!!!!!!莫名其妙
        $isPublic               = request('is_public','');
        $warningNumber          = request('warning_number',0);
        $keyword                = request('keyword','');
        $assemblageMaterialId                = request('assemblage_material_id','');



        ////////////////////////////////////////////////////
        /// 之下的字段不会同时出现!!!!!!
        /// 不用type和type_id来区分是因为app的需求
        //厂的供应商库存
        $sellerCompanyId        = request('seller_company_id',0);
        $sellerCompanyId        = intval($sellerCompanyId);
        //客户的库存
        $customerId             = request('customer_id',0);
        $customerId             = intval($customerId);
        //客户已客商角色登录app查看在某个厂中的材料库存时
        $saleCompanyId          = request('sale_company_id',0);
        $saleCompanyId          = intval($saleCompanyId);
        if($saleCompanyId > 0)
        {
            $where              = ['company_id'=>$saleCompanyId,'user_id'=>$userId];
            $customer           = Customer::getInfo($where);
            if(!$customer)
            {
                xThrow( ERR_UNKNOWN,'你在该厂的信息出现出错' );
            }
            $customerId         = $customer->id;
            $companyId          = $saleCompanyId;
        }
        //供应商角色看其在某个厂的材料库存
        $sellerCustomerId       = request('seller_customer_id',0);
        $sellerCustomerId       = intval($sellerCustomerId);
        ///////////////////////////////////////////////////

        $params                 = request()->only('category_id', 'product_name', 'product_no','page');
        $rules                  = [];
        $this->validateRequestParameters($params, $rules);

        $limit          = 10;
        $offset         = ($page - 1) * $limit;
        $where                  = [];

        //筛选
        if($assemblageMaterialId){
            $where['ygt_product.assemblage_material_id']    = $assemblageMaterialId;
        }

        $where['ygt_product.company_id']    = $companyId;
        if ($categoryIdStr)
        {
            $categoryIdArr      = explode(',', $categoryIdStr);
            foreach($categoryIdArr as $v)
            {
                if(!$v){//过滤空
                    continue;
                }

                $categoryModel  = new Category();
                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                $category       = collect($categoryArr);
                $tempCategoryIds = $category->map(function ($c) {
                    return $c['id'];
                })->toArray();
                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
            }
            $categoryIdArr      = array_unique($categoryIdArr);
            $where['ygt_product.category_id']   = ['in',$categoryIdArr];
        }
        if ($warningNumber)
        {
            $where[]            = ['whereRaw','number <= warning_number'];
        }
        if (in_array($isPublic,['yes','no']))
        {
            $where['ygt_product.is_public']     = $isPublic;
        }
        if($sellerCompanyId>0)
        {
            $where['ygt_product.seller_company_id'] = $sellerCompanyId;
        }
        $warehouseList          = [];
        $warehouseCount         = $warehouseSize = 0;
        if($customerId>0)
        {
            $where['ygt_product.customer_id']   = $customerId;
            $warehouseWhere     = ['customer_id'=>$customerId];
            $warehouseList      = \App\Eloquent\Ygt\Warehouse::getList($warehouseWhere,'',$limit,$offset)->toArray();
            //把成品的数据字段转换成和之前的材料字段,即返回给app的字段一致
            $customerWhere      = ['id'=>$customerId];
            $customer           = \App\Eloquent\Ygt\Customer::getInfo($customerWhere);
            if($customer)
            {
                $customerName       = $customer->customer_name;
                $warehouseList      = \App\Eloquent\Ygt\Product::chaneWarehouseList($warehouseList,$customerId,$customerName);
                $warehouseCount     = \App\Eloquent\Ygt\Warehouse::getCount($warehouseWhere);
                $warehouseSize      = count($warehouseList);
            }
        }
        if($keyword!='')
        {
            $where['ygt_product.product_name']   = ['like', '%'.$keyword.'%'];
        }
        if($sellerCustomerId>0)
        {
            $tempWhere          = [
                'company_id'=>$sellerCustomerId,
                'user_id'=>$userId,
            ];
            $sellerCompany      = SellerCompany::getInfo($tempWhere);
            if(!$sellerCompany)
            {
                xThrow( ERR_UNKNOWN,'信息出错' );
            }
            $sellerCompanyId        = $sellerCompany->id;
            $where['ygt_product.seller_company_id'] = $sellerCompanyId;
            $where['ygt_product.company_id']        = $sellerCustomerId;
        }

        $order          = request('order','id');
        $lift           = request('lift',1);
        $lift           = $lift === '0' ? 0 : 1;
        switch ($order)
        {
            case 'id':
                $orderBy = ['ygt_product.id'];
                break;
            case 'time':
                $orderBy = ['ygt_product.created_at'];
                break;
            case 'number':
                $orderBy = ['ygt_product.number'];
                break;
            default:
                $orderBy = ['ygt_product.id'];
                break;
        }
        $orderBy[]          = $lift == 1 ? 'desc' : 'asc';
        $lists              = [];
        $productCount       = 0;
        //成品数量不足时再取材料
        if($warehouseSize<$limit)
        {
            $productLimit       = $limit-$warehouseSize;
            //取列表
            $productList        = Product::getListByJoin($where,$productLimit,$offset,$orderBy)->toArray();
            //取总数
            $productCount       = Product::getCount($where);
            //取材料的自定义属性值
            $productIdArr       = [];
            foreach($productList as $key=>$val)
            {
                $productIdArr[] = $val['assemblage_material_id'];
                //供应商材料列表增加最近采购 -- 方案调整，这里不显示最近采购数据了。
                $productList[$key]['last_pruchase_price'] = "";
                $productList[$key]['total_price'] = $val['price']*$val['number'];
//                if($productList[$key]['total_price']>100000){
//                    $productList[$key]['total_price_txt'] = sprintf("%d万元",$productList[$key]['total_price']/10000);
//                }
//                else if($productList[$key]['total_price'] <1000){
//                    $productList[$key]['total_price_txt'] = sprintf("%d元",$productList[$key]['total_price']);
//                }
//                else{
//                    $productList[$key]['total_price_txt'] = sprintf("%d千元",$productList[$key]['total_price']/1000);
//                }
                $productList[$key]['total_price_txt'] = "¥".sprintf("%.2f",$productList[$key]['total_price']);
                $productList[$key]['price_txt'] = "¥".sprintf("%.2f",$val['price']);


                $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);
                if (!in_array($userInfo['privilege_id'], $privilegeIdList)) {
                    $productList[$key]['total_price_txt'] = "";
                    $productList[$key]['price_txt'] = "";
                }

//                if($sellerCompanyId){
//                    $tmpPurchaseMaterialRow = \App\Eloquent\Ygt\PurchaseMaterial::where(['material_id'=>$val['id']])->orderBy('created_at','desc')->first();
//                    $lastPurchasePrice = "";
//                    if($tmpPurchaseMaterialRow){
//                        $tmpAllPrice = $tmpPurchaseMaterialRow['price']*$tmpPurchaseMaterialRow['num'];
//                        $productList[$key]['last_pruchase_price'] = '最近采购单价¥'.$tmpPurchaseMaterialRow['price'].",总价¥".$tmpAllPrice;
//                    }
//                }

            }
            $where              = ['assemblage_material_id'=>['in',$productIdArr]];
//            $customFieldsArr    = ProductFields::getTransformListToArr($where);
            $customFieldsArr    = ProductFields::getTransformListToArr($where,1,'','',['id','asc'],1);

            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $lists              = Product::transformListByType($productList,$otherArr);
        }
        $count                  = $warehouseCount + $productCount;
        $listData               = array_merge($warehouseList,$lists);

        /**处理计量属性的值**/
        foreach ($listData as $key => $row){
            if(!empty($row['custom_fields'])){
                $isChange = false;
                foreach ($row['custom_fields'] as $tmpKey => $tmpRow){
                    if($tmpRow['is_compute']){
                        $isChange = true;
                        $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::where(['type'=>1,'material_id'=>$row['id'],'product_fields_id'=>$tmpRow['id']])->first();
                        if($tmpObj){
                            if($tmpObj['number']){
                                $listData[$key]['custom_fields'][$tmpKey]['field_value'] = $tmpObj['number'].$tmpRow['unit'];
                            }else{
                                //过滤这个字段
                                unset($listData[$key]['custom_fields'][$tmpKey]);
                            }
                        }else{
                            //过滤这个字段
                            unset($listData[$key]['custom_fields'][$tmpKey]);
                        }
                    }
                }

                //如果有计量属性调整重新处理字段
                if($isChange){
                    $firstText = $secondText = $thirdText = '';
                    if(isset($listData[$key]['custom_fields']))
                    {
                        $fieldsList         = array_values($listData[$key]['custom_fields']);
                        $listData[$key]['custom_fields'] = $fieldsList;//保存被过滤的结果

                        if(!empty($fieldsList))
                        {
                            if(isset($fieldsList[0]))
                            {
                                $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                            }
                            if(isset($fieldsList[1]))
                            {
                                $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                            }
                            if(isset($fieldsList[2]))
                            {
                                $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                            }
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;

                    $listData[$key]['custom_fields_text'] = $customFieldsText;

                }

            }
        }
        /**处理计量属性的值-结束**/

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }
    public function getProductDealList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId                   = request('company_id', 0);
        if(!$companyId){
            $companyId              = $userInfo->company_id;
        }

        //传参
        $page                   = request('page', 1);
        $categoryIdStr          = request('category_id',0);//多个逗号隔开!!!!!!!!!莫名其妙
        $isPublic               = request('is_public','');
        $warningNumber          = request('warning_number',0);
        $keyword                = request('keyword','');
        $assemblageMaterialId                = request('assemblage_material_id','');

        ////////////////////////////////////////////////////
        /// 之下的字段不会同时出现!!!!!!
        /// 不用type和type_id来区分是因为app的需求
        //厂的供应商库存
        $sellerCompanyId        = request('seller_company_id',0);
        $sellerCompanyId        = intval($sellerCompanyId);
        //客户的库存
        $customerId             = request('customer_id',0);
        $customerId             = intval($customerId);
        //客户已客商角色登录app查看在某个厂中的材料库存时
        $saleCompanyId          = request('sale_company_id',0);
        $saleCompanyId          = intval($saleCompanyId);
        if($saleCompanyId > 0)
        {
            $where              = ['company_id'=>$saleCompanyId,'user_id'=>$userId];
            $customer           = Customer::getInfo($where);
            if(!$customer)
            {
                xThrow( ERR_UNKNOWN,'你在该厂的信息出现出错' );
            }
            $customerId         = $customer->id;
            $companyId          = $saleCompanyId;
        }
        //供应商角色看其在某个厂的材料库存
        $sellerCustomerId       = request('seller_customer_id',0);
        $sellerCustomerId       = intval($sellerCustomerId);
        ///////////////////////////////////////////////////

        $params                 = request()->only('category_id', 'product_name', 'product_no','page');
        $rules                  = [];
        $this->validateRequestParameters($params, $rules);

        $limit          = 10;
        $offset         = ($page - 1) * $limit;
        $where                  = [];

        //筛选
        if($assemblageMaterialId){
            $where['ygt_product.assemblage_material_id']    = $assemblageMaterialId;
        }

        $where['ygt_product.company_id']    = $companyId;
        if ($categoryIdStr)
        {
            $categoryIdArr      = explode(',', $categoryIdStr);
            foreach($categoryIdArr as $v)
            {
                if(!$v){//过滤空
                    continue;
                }

                $categoryModel  = new Category();
                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                $category       = collect($categoryArr);
                $tempCategoryIds = $category->map(function ($c) {
                    return $c['id'];
                })->toArray();
                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
            }
            $categoryIdArr      = array_unique($categoryIdArr);
            $where['ygt_product.category_id']   = ['in',$categoryIdArr];
        }
        if ($warningNumber)
        {
            $where[]            = ['whereRaw','number <= warning_number'];
        }
        if (in_array($isPublic,['yes','no']))
        {
            $where['ygt_product.is_public']     = $isPublic;
        }
        if($sellerCompanyId>0)
        {
            $where['ygt_product.seller_company_id'] = $sellerCompanyId;
        }
        $warehouseList          = [];
        $warehouseCount         = $warehouseSize = 0;
        if($customerId>0)
        {
            $where['ygt_product.customer_id']   = $customerId;
            $warehouseWhere     = ['customer_id'=>$customerId];
            $warehouseList      = \App\Eloquent\Ygt\Warehouse::getList($warehouseWhere,'',$limit,$offset)->toArray();
            //把成品的数据字段转换成和之前的材料字段,即返回给app的字段一致
            $customerWhere      = ['id'=>$customerId];
            $customer           = \App\Eloquent\Ygt\Customer::getInfo($customerWhere);
            if($customer)
            {
                $customerName       = $customer->customer_name;
                $warehouseList      = \App\Eloquent\Ygt\Product::chaneWarehouseList($warehouseList,$customerId,$customerName);
                $warehouseCount     = \App\Eloquent\Ygt\Warehouse::getCount($warehouseWhere);
                $warehouseSize      = count($warehouseList);
            }
        }
        if($keyword!='')
        {
            $where['ygt_product.product_name']   = ['like', '%'.$keyword.'%'];
        }
        if($sellerCustomerId>0)
        {
            $tempWhere          = [
                'company_id'=>$sellerCustomerId,
                'user_id'=>$userId,
            ];
            $sellerCompany      = SellerCompany::getInfo($tempWhere);
            if(!$sellerCompany)
            {
                xThrow( ERR_UNKNOWN,'信息出错' );
            }
            $sellerCompanyId        = $sellerCompany->id;
            $where['ygt_product.seller_company_id'] = $sellerCompanyId;
            $where['ygt_product.company_id']        = $sellerCustomerId;
        }

        $order          = request('order','id');
        $lift           = request('lift',1);
        $lift           = $lift === '0' ? 0 : 1;
        switch ($order)
        {
            case 'id':
                $orderBy = ['ygt_product.id'];
                break;
            case 'time':
                $orderBy = ['ygt_product.created_at'];
                break;
            case 'number':
                $orderBy = ['ygt_product.number'];
                break;
            default:
                $orderBy = ['ygt_product.id'];
                break;
        }
        $orderBy[]          = $lift == 1 ? 'desc' : 'asc';
        $lists              = [];
        $productCount       = 0;
        //成品数量不足时再取材料
        if($warehouseSize<$limit)
        {
            $productLimit       = $limit-$warehouseSize;
            //取列表
            $productList        = Product::getListByJoin($where,$productLimit,$offset,$orderBy)->toArray();
            //取总数
            $productCount       = Product::getCount($where);
            //取材料的自定义属性值
            $productIdArr       = [];
            foreach($productList as $key=>$val)
            {
                $productIdArr[] = $val['assemblage_material_id'];
            }
            $where              = ['assemblage_material_id'=>['in',$productIdArr]];
//            $customFieldsArr    = ProductFields::getTransformListToArr($where);
            $customFieldsArr    = ProductFields::getTransformListToArr($where,1,'','',['id','asc'],1);
            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $lists              = Product::transformListByType($productList,$otherArr);
        }
        $count                  = $warehouseCount + $productCount;
        $listData               = array_merge($warehouseList,$lists);



        /**处理计量属性的值**/
        foreach ($listData as $key => $row){
            if(!empty($row['custom_fields'])){
                $isChange = false;
                foreach ($row['custom_fields'] as $tmpKey => $tmpRow){
                    if($tmpRow['is_compute']){
                        $isChange = true;
                        $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::where(['type'=>1,'material_id'=>$row['id'],'product_fields_id'=>$tmpRow['id']])->first();
                        if($tmpObj){
                            if($tmpObj['number']){
                                $listData[$key]['custom_fields'][$tmpKey]['field_value'] = $tmpObj['number'].$tmpRow['unit'];
                            }else{
                                //过滤这个字段
                                unset($listData[$key]['custom_fields'][$tmpKey]);
                            }
                        }else{
                            //过滤这个字段
                            unset($listData[$key]['custom_fields'][$tmpKey]);
                        }
                    }
                }

                //如果有计量属性调整重新处理字段
                if($isChange){
                    $firstText = $secondText = $thirdText = '';
                    if(isset($listData[$key]['custom_fields']))
                    {
                        $fieldsList         = array_values($listData[$key]['custom_fields']);
                        $listData[$key]['custom_fields'] = $fieldsList;//保存被过滤的结果

                        if(!empty($fieldsList))
                        {
                            if(isset($fieldsList[0]))
                            {
                                $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                            }
                            if(isset($fieldsList[1]))
                            {
                                $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                            }
                            if(isset($fieldsList[2]))
                            {
                                $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                            }
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;

                    $listData[$key]['custom_fields_text'] = $customFieldsText;

                }

            }
        }
        /**处理计量属性的值-结束**/

        $listDealData = [];
        $listDealData['list'] = $listData;

        //是否隐藏添加按钮
        $isHideAddButton = 1;
        //只有下单人有创建材料权限
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $isHideAddButton = 0;
        }

        $listDealData['is_hide_add_button'] = $isHideAddButton;

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listDealData, $pagingData);
    }

    public function getProductInfo()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $productId          = request('product_id',0);
        if(!$userInfo || !$productId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = [
            'ygt_product.company_id'=>$companyId,
            'ygt_product.id'=>$productId
        ];
        $product            = Product::getEditInfo($where);
        if(!$product)
        {
            xThrow(ERR_UNKNOWN,'材料信息出错');
        }
        $info               = $product->toArray();
        $imagePath          = \App\Engine\Func::getImgUrlHttp($info['img_url']);
        $info['img_path']   = $imagePath;
        return $info;
    }

    public  function addProduct(){
        $params = request()->only('product_name', 'product_no', 'barcode', 'category_id', 'img_id', 'unit');
        $params['img_id'] = $params['img_id']?$params['img_id']:0;
        $params['unit'] = $params['unit']?$params['unit']:'';

        $user_id        = Func::getHeaderValueByName( 'userid' );
        $info           = DepartmentUser::getCurrentInfo( $user_id );

        $productModel = new Product();
        $rules = [
            'product_name' => 'required',
            'unit' => 'required',
            'category_id' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);

        $params['product_no'] = $params['product_no']?$params['product_no']:EngineProduct::createProductNo();

        $productModel = new Product();
        $productInfo = $productModel->getProductInfoByNo($params['product_no']);
        if (!$productInfo or !$productInfo->toArray()) {
            $productData = [
                'product_name' => $params['product_name'],
                'product_no' => $params['product_no'],
                'unit' => $params['unit'],
                'category_id' => $params['category_id'],
                'company_id' => $info->company_id,
                'img_id' => $params['img_id'],
            ];


            if (!$productInfo = $productModel->addProduct($productData)) {
                xThrow(ERR_PRODUCT_CREATE_FAIL);
            }

            //自定义字段
            $fields = request('custom_fields');
            $fields = json_decode(htmlspecialchars_decode($fields), true);
            $ProductFieldsModel = new ProductFields();
            foreach ($fields as $v){
                $comumnName = EngineProduct::getFieldColumn($v['field_type']);
                $fieldData = [
                    'product_id' => $productInfo->id,
                    'field_name' => $v['field_name'],
                    'field_type' => $v['field_type'],
                    $comumnName => $v['field_value']
                ];
                $ProductFieldsModel->insertData($fieldData);
            }

            $returnData = [
                'msg'=>'ok',
                'product_id'=>$productInfo->id
            ];
            return $returnData;

        }else{
            xThrow(ERR_PRODUCT_NO_IS_EXIST);
        }
    }
    //修改材料,只允许修改部分属性
    public function editProduct()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $productId          = request('id',0);
        $productName        = request('product_name','');
        $categoryId         = request('category_id',0);
        $imgId              = request('img_id',0);
        $isCustomer         = request('is_customer',1);
        $customerId         = request('customer_id',0);
        $customerId         = intval($customerId);
        if($isCustomer == 0)
        {
            $customerId     = 0;
        }else{
            if($customerId == 0){
                $isCustomer = 0;
            }
        }
        $isSeller           = request('is_seller',1);
        $sellerId           = request('seller_id',0);
        $sellerId           = intval($sellerId);
        if($isSeller == 0)
        {
            $sellerId     = 0;
        }else{
            if($sellerId == 0){
                $isSeller = 0;
            }
        }
        if(!$userInfo || !$productId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        //一些必填字段
        $requestMustArr     = [
            'product_name'=>'材料名称不能为空',
            'category_id'=>'分类名称',
        ];
        $requestData        = request()->all();
        foreach($requestMustArr as $key=>$val)
        {
            if(!isset($requestData[$key]) || empty($requestData[$key]))
            {
                $requestMustMsg     = $val;
                xThrow( ERR_PARAMETER,$requestMustMsg );
            }
        }
        $where              = ['company_id'=>$companyId,'id'=>$productId];
        $product            = Product::getInfo($where);
        if(!$product)
        {
            xThrow(ERR_UNKNOWN,'材料信息出错');
        }
        $productCustomerId  = $product->customer_id;
        if($productCustomerId!=0 && $customerId!=0 && $productCustomerId!=$customerId)
        {
            xThrow(ERR_UNKNOWN,'客户不允许修改');
        }
        $productSellerCompanyId = $product->seller_company_id;
        if($productSellerCompanyId!=0 && $sellerId!=0 && $productSellerCompanyId!=$sellerId)
        {
            xThrow(ERR_UNKNOWN,'供应商不允许修改');
        }
        $customerId         = $customerId==0 ? $productCustomerId : $customerId;
        $sellerId           = $sellerId==0 ? $productSellerCompanyId : $sellerId;
        $productData        = [
            'product_name'=>$productName,
            'category_id'=>$categoryId,
            'img_id'=>$imgId,
            'is_customer'=>$isCustomer,
            'customer_id'=>$customerId,
            'is_seller'=>$isSeller,
            'seller_company_id'=>$sellerId,
        ];
        $where              = ['id'=>$productId];
        $updateResult       = Product::updateOneData($where,$productData);
        if(!$updateResult)
        {
            xThrow(ERR_UNKNOWN,'修改失败');
        }
        return ['message'=>'修改成功'];
    }

    public function deleteProduct(){
        $params = request()->only('product_id','product_no');

        $productModel = new Product();

        if($params['product_id']){
            $where['id'] = $params['product_id'];
        }else if($params['product_no']){
            $where['product_no'] = $params['product_no'];
        }else{
            xThrow(ERR_PRODUCT_NOT_EXIST);
        }

        if($productModel->del($where)){
            return 'ok';
        }else{
            xThrow(ERR_PRODUCT_DELETE_FAIL);
        }
    }

    public function printer(){

        $printInfo  = request('products');
        $printInfo = json_decode(htmlspecialchars_decode($printInfo), true);

        Log::info($printInfo);

        $productModel = new Product();
        $resultData = [];
        foreach ($printInfo as $val){

            if($productInfo = $productModel->getProductInfoById($val['product_id'])){
                KmPrinter::text($productInfo->product_name);
                KmPrinter::text($productInfo->product_no);
                $productFields = ProductFields::where('product_id',$val['product_id'])->get();
                foreach ($productFields as $pval){
                    $comumnName = EngineProduct::getFieldColumn($pval->field_type);
                    KmPrinter::text($pval->field_name.':'.$pval->$comumnName);
                }
                $qrcodeInfo = [
                    'm'=>$productInfo->product_no,
                ];
                if(isset($val['product_number'])){
                    $qrcodeInfo['n'] = $val['product_number'];
                }
                $tempQrcode = [];
                foreach ($qrcodeInfo as $key=>$val){
                    $tempQrcode[] = $key.':'.$val;
                }
                $qrcodeStr = implode(',',$tempQrcode);
                KmPrinter::qrcode($qrcodeStr);
                $tmp = [
                    'number'=> isset($val['number'])?$val['number']:1,
                    'pinfo'=>KmPrinter::p()
                ];
                $resultData[] = $tmp;
            }
        }

        return $resultData;
    }


    //获取集合产品列表
    public function getAssemblageMaterialList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId              = $userInfo->company_id;

        //传参
        $page                   = request('page', 1);
        $categoryIdStr          = request('category_id',0);//多个逗号隔开!!!!!!!!!莫名其妙
        $isPublic               = request('is_public','');
        $warningNumber          = request('warning_number',0);
        $keyword                = request('keyword','');
        $sellerCompanyId                = request('seller_company_id','');

        $isActive                = request('is_active',0);
        ////////////////////////////////////////////////////
        /// 之下的字段不会同时出现!!!!!!
        /// 不用type和type_id来区分是因为app的需求

        $params                 = request()->only('category_id', 'product_name', 'product_no','page');
        $rules                  = [];
        $this->validateRequestParameters($params, $rules);

        $limit          = 10;
        $offset         = ($page - 1) * $limit;
        $where                  = [];
        $where['ygt_assemblage_material.company_id']    = $companyId;
        //新增通过供应商的主营业务过滤 zhuyujun 20181113
        if($sellerCompanyId){
            $assemblageMaterialIdArr = \App\Eloquent\Ygt\SellerCompanyMaterial::where(['seller_company_id'=>$sellerCompanyId])->get()->pluck('assemblage_material_id');
            $where['ygt_assemblage_material.id']   = ['in',$assemblageMaterialIdArr];
        }


        if ($categoryIdStr)
        {
            $categoryIdArr      = explode(',', $categoryIdStr);
            foreach($categoryIdArr as $v)
            {
                if(!$v){//过滤空
                    continue;
                }

                $categoryModel  = new Category();
                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                $category       = collect($categoryArr);
                $tempCategoryIds = $category->map(function ($c) {
                    return $c['id'];
                })->toArray();
                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
            }
            $categoryIdArr      = array_unique($categoryIdArr);
            $where['ygt_assemblage_material.category_id']   = ['in',$categoryIdArr];
        }
        if ($warningNumber)
        {
            $where[]            = ['whereRaw','number <= warning_number'];
        }
        if (in_array($isPublic,['yes','no']))
        {
            $where['ygt_assemblage_material.is_public']     = $isPublic;
        }
        $warehouseList          = [];
        $warehouseCount         = $warehouseSize = 0;
        if($keyword!='')
        {
            $where['ygt_assemblage_material.product_name']   = ['like', '%'.$keyword.'%'];
        }

        $order          = request('order','id');
        $lift           = request('lift',1);
        $lift           = $lift === '0' ? 0 : 1;
        switch ($order)
        {
            case 'id':
                $orderBy = ['ygt_assemblage_material.id'];
                break;
            case 'time':
                $orderBy = ['ygt_assemblage_material.created_at'];
                break;
            case 'number':
                $orderBy = ['ygt_assemblage_material.number'];
                break;
            default:
                $orderBy = ['ygt_assemblage_material.id'];
                break;
        }
        $orderBy[]          = $lift == 1 ? 'desc' : 'asc';
        $lists              = [];
        $productCount       = 0;

        //成品数量不足时再取材料
        if($warehouseSize<$limit)
        {
            $productLimit       = $limit-$warehouseSize;
            //取列表
            $productList        = \App\Eloquent\Ygt\AssemblageMaterial::getListByJoinAssemblageMaterial($where,$productLimit,$offset,$orderBy)->toArray();
            //取总数
            $productCount       = \App\Eloquent\Ygt\AssemblageMaterial::getData($where)->count();

            //取材料的自定义属性值
            $productIdArr       = [];
            foreach($productList as $key=>$val)
            {
                $productIdArr[] = $val['id'];
            }
            $where              = ['assemblage_material_id'=>['in',$productIdArr]];
            $customFieldsArr    = ProductFields::getTransformListToArr($where,1,'','',['id','asc'],1);

            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $isAssemblageMaterial = 1;
            $lists              = Product::transformListByType($productList,$otherArr,1,$isAssemblageMaterial);
        }


        $count                  = $warehouseCount + $productCount;
        $listData               = array_merge($warehouseList,$lists);

//        //集合材料属性特殊处理，显示所有属性
//        foreach ($listData as $tmpKey => $tmpRow){
//            $tmpCustomFieldsText = "";
//            foreach ($tmpRow['custom_fields'] as  $tmpCustomFieldsRow){
//                $tmpCustomFieldsText.= $tmpCustomFieldsRow['field_name'].':'.$tmpCustomFieldsRow['field_value']." ";
//            }
//            $listData[$tmpKey]['custom_fields_text'] = $tmpCustomFieldsText;
//        }



        //添加集合材料下属的供应商材料
        foreach ($listData as $key => $row){
            $assemblageMaterialId = $row['id'];
            if($isActive == 1){//主动采购
                $tmpProductList = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$assemblageMaterialId,'company_id'=>$companyId])->get();
            }
            else{
                $tmpProductList = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$assemblageMaterialId])->get();
            }
            $supplierRow = [];
            $total_money = 0;//总的价格
            foreach ($tmpProductList as $tmpProductRow){
                $sellerCompanyId = $tmpProductRow['seller_company_id'];
                //获取供应商信息
                $tmpSellerCompanyRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$sellerCompanyId])->first();
                if($tmpSellerCompanyRow){
                    $tmpYNum = 0;
                    $where = [];
                    $where[] = ['product_id','=',$tmpProductRow['id']];
                    $tmpQrcodeList = \App\Eloquent\Ygt\Qrcode::where($where)->get();
                    foreach ($tmpQrcodeList as $tmpQrcodeRow){
                        if($tmpQrcodeRow['now_number'] != $tmpQrcodeRow['total_number']){
                            $tmpYNum += $tmpQrcodeRow['now_number'];
                        }
                    }

                    $supplierRow[]=[
                        'seller_company_title' => $tmpSellerCompanyRow['title'],
                        'material_id' => $tmpProductRow['id'],
                        'number'=> $tmpProductRow['number'].$tmpProductRow['unit'],
                        'y_number'=> $tmpYNum.$tmpProductRow['unit'],
                        'price'=>'¥'.$tmpProductRow['price'],
                    ];
                }
                $total_money+=$tmpProductRow['price']*$tmpProductRow['number'];
            }
            $listData[$key]['supplier_list'] = $supplierRow;
            $listData[$key]['supplier_number'] = count($supplierRow);
            //$listData[$key]['supplier_number_txt'] = sprintf("共%d个供应商",$listData[$key]['supplier_number']);
            $listData[$key]['supplier_number_txt'] = sprintf("共%d个sku",$listData[$key]['supplier_number']);
            $listData[$key]['total_money'] = $total_money;
//            if($listData[$key]['total_money']>100000){
//                $listData[$key]['total_money_txt'] = sprintf("%d万元",$listData[$key]['total_money']/10000);
//            }
//            else if($listData[$key]['total_money'] < 1000){
//                $listData[$key]['total_money_txt'] = sprintf("%d元",$listData[$key]['total_money']);
//            }
//            else{
//                $listData[$key]['total_money_txt'] = sprintf("%d千元",$listData[$key]['total_money']/1000);
//            }

            $listData[$key]['total_money_txt'] = "¥".sprintf("%.2f",$listData[$key]['total_money']);

            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);
            if (!in_array($userInfo['privilege_id'], $privilegeIdList)) {
                $listData[$key]['total_money_txt'] = "";
            }
        }



        /**处理计量属性的值**/
        foreach ($listData as $key => $row){
            if(!empty($row['custom_fields'])){
                $isChange = false;
                foreach ($row['custom_fields'] as $tmpKey => $tmpRow){
                    if($tmpRow['is_compute']){
                        $isChange = true;//是否有变化，需要处理记录属性字段
                        $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::where(['type'=>2,'material_id'=>$row['id'],'product_fields_id'=>$tmpRow['id']])->first();
                        if($tmpObj){
                            if($tmpObj['number']){
                                $listData[$key]['custom_fields'][$tmpKey]['field_value'] = $tmpObj['number'].$tmpRow['unit'];
                            }else{
                                //过滤这个字段
                                unset($listData[$key]['custom_fields'][$tmpKey]);
                            }
                        }else{
                            //过滤这个字段
                            unset($listData[$key]['custom_fields'][$tmpKey]);
                        }
                    }
                }

                //如果有计量属性调整重新处理字段
                if($isChange){
                    $firstText = $secondText = $thirdText = '';
                    if(isset($listData[$key]['custom_fields']))
                    {
                        $fieldsList         = array_values($listData[$key]['custom_fields']);
                        $listData[$key]['custom_fields'] = $fieldsList;//保存被过滤的结果

                        if(!empty($fieldsList))
                        {
                            if(isset($fieldsList[0]))
                            {
                                $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                            }
                            if(isset($fieldsList[1]))
                            {
                                $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                            }
                            if(isset($fieldsList[2]))
                            {
                                $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                            }
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;

                    $listData[$key]['custom_fields_text'] = $customFieldsText;
                }
            }
        }
        /**处理计量属性的值-结束**/

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }

    //获得筒料规格相匹配的集合材料id
    private function getAMIdByTGG($width){
        $width_txt = '宽度';

        $obj = ProductFields::where('assemblage_material_id','>',0);
        $obj = $obj
            ->where(function ($query) use ($width_txt,$width) {
                $query->where('field_name', '=',\DB::raw('"'.$width_txt.'"'))
                    ->where('varchar', '=',\DB::raw('"'.$width.'"'));
            })
            ->groupBy(['assemblage_material_id']);


        $assemblageMaterialIdList = $obj->get(['assemblage_material_id'])->pluck('assemblage_material_id')->toArray();
        return $assemblageMaterialIdList;
    }
    //获得膜规格相匹配的集合材料id
    private function getAMIdByMGG($width){
        $width_txt = '膜宽';
        $obj = ProductFields::where('assemblage_material_id','>',0);
        $obj = $obj->where(function ($query) use ($width_txt,$width) {
                $query->where('field_name', '=',\DB::raw('"'.$width_txt.'"'))
                    ->where('varchar', '=',\DB::raw('"'.$width.'"'));
            })
            ->groupBy(['assemblage_material_id']);

        $assemblageMaterialIdList = $obj->get([\DB::raw('count(1) as num'),'assemblage_material_id'])->pluck('assemblage_material_id')->toArray();
        return $assemblageMaterialIdList;
    }


    //获取集合产品列表
    public function getAssemblageMaterialDealList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }

        //传参
        $page                   = request('page', 1);
        $categoryIdStr          = request('category_id',0);//多个逗号隔开!!!!!!!!!莫名其妙
        $isPublic               = request('is_public','');
        $warningNumber          = request('warning_number',0);
        $keyword                = request('keyword','');
        $isHideCommon                = request('is_hide_common','');

        $customerId = request('customer_id',0);
        $filterType = request('filter_type',0);

        $companyId = request('company_id',0);
        $plateId = request('plate_id',0);
        if(!$companyId){
            $companyId              = $userInfo->company_id;
        }

        ////////////////////////////////////////////////////
        /// 之下的字段不会同时出现!!!!!!
        /// 不用type和type_id来区分是因为app的需求

        $params                 = request()->only('category_id', 'product_name', 'product_no','page');
        $rules                  = [];
        $this->validateRequestParameters($params, $rules);

        $limit          = 10;
        $offset         = ($page - 1) * $limit;
        $where                  = [];
        $where['ygt_assemblage_material.company_id']    = $companyId;
        if ($categoryIdStr)
        {
            $categoryIdArr      = explode(',', $categoryIdStr);
            foreach($categoryIdArr as $v)
            {
                if(!$v){//过滤空
                    continue;
                }

                $categoryModel  = new Category();
                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                $category       = collect($categoryArr);
                $tempCategoryIds = $category->map(function ($c) {
                    return $c['id'];
                })->toArray();

                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);


            }
            $categoryIdArr      = array_unique($categoryIdArr);
            if(count($categoryIdArr)){
                $where['ygt_assemblage_material.category_id']   = ['in',$categoryIdArr];
            }
        }
        if ($warningNumber)
        {
            $where[]            = ['whereRaw','number <= warning_number'];
        }
        if (in_array($isPublic,['yes','no']))
        {
            $where['ygt_assemblage_material.is_public']     = $isPublic;
        }

        if($keyword!='')
        {
            $where['ygt_assemblage_material.product_name']   = ['like', '%'.$keyword.'%'];
        }

        $order          = request('order','id');
        $lift           = request('lift',1);
        $lift           = $lift === '0' ? 0 : 1;
        switch ($order)
        {
            case 'id':
                $orderBy = ['ygt_assemblage_material.id'];
                break;
            case 'time':
                $orderBy = ['ygt_assemblage_material.created_at'];
                break;
            case 'number':
                $orderBy = ['ygt_assemblage_material.number'];
                break;
            default:
                $orderBy = ['ygt_assemblage_material.id'];
                break;
        }
        $orderBy[]          = $lift == 1 ? 'desc' : 'asc';
        //筛选客户材料和本公司材料
        if($filterType){
            if($filterType == 1){
                if($customerId){
                    $tmpWhere = [];
                    $tmpWhere[] = ['company_id','=',$companyId];
                    $tmpWhere[] = ['customer_id','=',$customerId];
                    $tmpWhere[] = ['assemblage_material_id','>',0];
                    $assemblageMaterialIdList = \App\Eloquent\Ygt\Product::where($tmpWhere)->get()->pluck('assemblage_material_id')->toArray();
                    //$where  = ['ygt_assemblage_material.id'=>['in',$assemblageMaterialIdList]];
                    $where['ygt_assemblage_material.id']=['in',$assemblageMaterialIdList];
                }
            }

            if($filterType == 2){
                $tmpWhere = [];
                $tmpWhere[] = ['company_id','=',$companyId];
                $tmpWhere[] = ['customer_id','=',0];
                $tmpWhere[] = ['assemblage_material_id','>',0];
                $assemblageMaterialIdList = \App\Eloquent\Ygt\Product::where($tmpWhere)->get()->pluck('assemblage_material_id')->toArray();
                //$where  = ['ygt_assemblage_material.id'=>['in',$assemblageMaterialIdList]];
                $where['ygt_assemblage_material.id']=['in',$assemblageMaterialIdList];
            }
        }


        $lists              = [];//数据列表
        $count = 0;//数据总数
        $curr_count = 0;//当前已有数据数量
        $productLimit = $limit;//需要的数据总量
        //$offset; 取数据需要跳过的数量
        //$page;//页码
        //$limit; //每次查询要取的数量
        $other_count = 0;//其他数据的总数量

        //根据版优先推荐规格匹配的材料
        if($plateId){
            $plateInfo = Plate::getPlateInfo($plateId);
            if($plateInfo){
                $plateInfo = $plateInfo->toArray();
            }

            $tempAssemblageMaterialIdList = [];
            //膜规格
            if(!empty($plateInfo['membrane_specification'])){
                $tempWidth = $plateInfo['membrane_specification'];
                $tempAssemblageMaterialIdList = $this->getAMIdByMGG($tempWidth);
            }
            //片料规格
            if(!empty($plateInfo['chip_specification_length'])){
                $tempArr = explode(',',$plateInfo['chip_specification_length']);
                if(count($tempArr) == 2){
                    $tempAssemblageMaterialIdList2 = $this->getAMIdByTGG($tempArr[0]);
                    $tempAssemblageMaterialIdList=array_merge($tempAssemblageMaterialIdList,$tempAssemblageMaterialIdList2);
                }
            }

            //优先材料条件
            $tempWhere = $where;
            //说明上面有ygt_assemblage_material.id 这个条件 现在要用需要特殊处理
            if(isset($where['ygt_assemblage_material.id'])){
                $assemblageMaterialIdList = $where['ygt_assemblage_material.id'][1];
                //集合材料的id限定在两次的交集
                $tempAssemblageMaterialIdListIntersect = array_intersect($tempAssemblageMaterialIdList,$assemblageMaterialIdList);
                $tempWhere['ygt_assemblage_material.id'] = ['in',$tempAssemblageMaterialIdListIntersect];
                //原来的条件 集合材料的id要排除交集中的数据
                $assemblageMaterialIdListDiff = array_diff($assemblageMaterialIdList,$tempAssemblageMaterialIdListIntersect);
                $where['ygt_assemblage_material.id'] = ['in',$assemblageMaterialIdListDiff];
            }
            else{
                $tempWhere['ygt_assemblage_material.id'] = ['in',$tempAssemblageMaterialIdList];
                $where['ygt_assemblage_material.id'] = ['notIn',$tempAssemblageMaterialIdList];
            }

            //取列表
            $priorProductList        = \App\Eloquent\Ygt\AssemblageMaterial::getListByJoinAssemblageMaterial($tempWhere,$limit,$offset,$orderBy)->toArray();
            //取总数
            $priorProductCount       = \App\Eloquent\Ygt\AssemblageMaterial::getData($tempWhere)->count();

            //取材料的自定义属性值
            $productIdArr       = [];
            foreach($priorProductList as $key=>$val)
            {
                $productIdArr[] = $val['id'];
            }
            $tempWhere              = ['assemblage_material_id'=>['in',$productIdArr]];
            $customFieldsArr    = ProductFields::getTransformListToArr($tempWhere,1,'','',['id','asc'],1);

            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $isAssemblageMaterial = 1;
            $priorProductList              = Product::transformListByType($priorProductList,$otherArr,1,$isAssemblageMaterial);

            $lists          = array_merge($lists,$priorProductList);
            $curr_count     = count($lists);//当前已有数据总量

            $count+=$priorProductCount;//数据总数
            $other_count+=$priorProductCount;
        }

        //成品数量不足时再取材料
        //取总数
        $productCount       = \App\Eloquent\Ygt\AssemblageMaterial::getData($where)->count();
        $count+=$productCount;//数据总数
        $limit       = $productLimit-$curr_count;
        //还需要取 $limit 条数据
        if($limit>0)
        {
            //跳过的位置偏移
            //没有其他数据
            if($other_count == 0){
                $offset = $offset;
            }
            //有其他数据
            else{
                //本次取的有其他数据
                if($curr_count>0){
                    $offset=0;
                }
                //本次没有取其他数据
                else{
                    $offset-=$other_count;
                }
            }


            //取列表
            $productList        = \App\Eloquent\Ygt\AssemblageMaterial::getListByJoinAssemblageMaterial($where,$limit,$offset,$orderBy)->toArray();

            //取材料的自定义属性值
            $productIdArr       = [];
            foreach($productList as $key=>$val)
            {
                $productIdArr[] = $val['id'];
            }
            $where              = ['assemblage_material_id'=>['in',$productIdArr]];
//            $customFieldsArr    = ProductFields::getTransformListToArr($where);
            $customFieldsArr    = ProductFields::getTransformListToArr($where,1,'','',['id','asc'],1);

            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $isAssemblageMaterial = 1;
            $productList              = Product::transformListByType($productList,$otherArr,1,$isAssemblageMaterial);

            $listData               = array_merge($lists,$productList);
            $curr_count     = count($listData);//当前已有数据总量
            $other_count+=$productCount;
        }

        //添加集合材料下属的供应商材料
        foreach ($listData as $key => $row){
            $assemblageMaterialId = $row['id'];
            $tmpProductList = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$assemblageMaterialId])->get();

            //默认通用
            $supplierNum = 0;
            $supplierYNum = 0;

            $supplierRow_ty = [];
            if(!$isHideCommon){
                $supplierRow_ty[] = [
                    'seller_company_title' => '不限供应商',
                    'material_id' => "A".$assemblageMaterialId,
                    'number'=> $supplierNum.$row['unit'],
                    'y_number'=> $supplierYNum.$row['unit'],
                    'price'=>'¥0',
                    'attach_type'=>3,//通用
                ];
            }

            //客户
            $supplierRow_c = [];

            //本厂
            $supplierRow_s = [];

            //其他
            $supplierRow_o = [];

            foreach ($tmpProductList as $tmpProductRow){
                $sellerCompanyId = $tmpProductRow['seller_company_id'];
                //获取供应商信息
                $tmpSellerCompanyRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$sellerCompanyId])->first();
                if($tmpSellerCompanyRow){
                    //获取余品数量（余品只在扫码领料、余料回退过程中产生 -- 获取码对应的余品数量）
                    $tmpYNum = 0;
                    $where = [];
                    $where[] = ['product_id','=',$tmpProductRow['id']];
                    $tmpQrcodeList = \App\Eloquent\Ygt\Qrcode::where($where)->get();
                    foreach ($tmpQrcodeList as $tmpQrcodeRow){
                        if($tmpQrcodeRow['now_number'] != $tmpQrcodeRow['total_number']){
                            $tmpYNum += $tmpQrcodeRow['now_number'];
                        }
                    }

                    //预留统计规则
                    //2019-01-23 这个预留留的好，现在的统计规则是要求，选择“不限”是，只计算本厂的库存数量和余品数量
                    if($tmpProductRow['customer_id'] == 0){
                        $supplierYNum += $tmpYNum;
                        $supplierNum += $tmpProductRow['number'];
                    }


                    $supplierRowT=[
                        'seller_company_title' => $tmpSellerCompanyRow['title'],
                        'material_id' => $tmpProductRow['id'],
                        'number'=> $tmpProductRow['number'].$tmpProductRow['unit'],
                        'y_number'=> $tmpYNum.$tmpProductRow['unit'],
                        'price'=>'¥'.$tmpProductRow['price'],
                    ];

                    //假如是客户自己的材料
                    if($customerId && $customerId == $tmpProductRow['customer_id']){
                        $supplierRowT['attach_type'] = 1;//客户
                        $supplierRow_c[] = $supplierRowT;
                        continue;
                    }

                    //假如是本厂的材料
                    if($tmpProductRow['customer_id'] == 0){
                        $supplierRowT['attach_type'] = 2;//本厂
                        $supplierRow_s[] = $supplierRowT;
                        continue;
                    }

                    //其他的
                    $supplierRowT['attach_type'] = 4;//其他未知的
                    //2019-01-23 对于不属于当前客户，不属于本厂的材料，不显示,故注释掉下面此句
                    //$supplierRow_o[] = $supplierRowT;
                }
            }

            //修改不限供应商的数据
            if(!$isHideCommon){
                $supplierRow_ty[0]['number'] = $supplierNum.$row['unit'];
                $supplierRow_ty[0]['y_number'] = $supplierYNum.$row['unit'];
            }


            //将数据合到一个数组
            $supplierRow = [];
            if(!empty($supplierRow_c)){
                $supplierRow = array_merge($supplierRow,$supplierRow_c);
            }
            if(!empty($supplierRow_s)){
                $supplierRow = array_merge($supplierRow,$supplierRow_s);
            }
            if(!empty($supplierRow_o)){
                $supplierRow = array_merge($supplierRow,$supplierRow_o);
            }
            if(!empty($supplierRow_ty)){
                $supplierRow = array_merge($supplierRow,$supplierRow_ty);
            }

            $listData[$key]['supplier_list'] = $supplierRow;
            $listData[$key]['supplier_number'] = count($supplierRow);
            //$listData[$key]['supplier_number_txt'] = sprintf("共%d个供应商",$listData[$key]['supplier_number']);
            $listData[$key]['supplier_number_txt'] = sprintf("共%d个sku",$listData[$key]['supplier_number']);
        }


        /**处理计量属性的值**/
        foreach ($listData as $key => $row){
            if(!empty($row['custom_fields'])){
                $isChange = false;
                foreach ($row['custom_fields'] as $tmpKey => $tmpRow){
                    if($tmpRow['is_compute']){
                        $isChange = true;
                        $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::where(['type'=>2,'material_id'=>$row['id'],'product_fields_id'=>$tmpRow['id']])->first();
                        if($tmpObj){
                            if($tmpObj['number']){
                                $listData[$key]['custom_fields'][$tmpKey]['field_value'] = $tmpObj['number'].$tmpRow['unit'];
                            }else{
                                //过滤这个字段
                                unset($listData[$key]['custom_fields'][$tmpKey]);
                            }
                        }else{
                            //过滤这个字段
                            unset($listData[$key]['custom_fields'][$tmpKey]);
                        }
                    }
                }

                //如果有计量属性调整重新处理字段
                if($isChange){
                    $firstText = $secondText = $thirdText = '';
                    if(isset($listData[$key]['custom_fields']))
                    {
                        $fieldsList         = array_values($listData[$key]['custom_fields']);
                        $listData[$key]['custom_fields'] = $fieldsList;//保存被过滤的结果

                        if(!empty($fieldsList))
                        {
                            if(isset($fieldsList[0]))
                            {
                                $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                            }
                            if(isset($fieldsList[1]))
                            {
                                $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                            }
                            if(isset($fieldsList[2]))
                            {
                                $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                            }
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;

                    $listData[$key]['custom_fields_text'] = $customFieldsText;
                }
            }
        }
        /**处理计量属性的值-结束**/

        $listDealData = [];
        $listDealData['list'] = $listData;

        //是否隐藏添加按钮
        $isHideAddButton = 1;
        //只有下单人有创建材料权限
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $isHideAddButton = 0;
        }

        $listDealData['is_hide_add_button'] = $isHideAddButton;

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listDealData, $pagingData);
    }

    //新加SKU（实际）材料
    public function submitActualMateril(){
        $assemblageMaterialId = request('assemblage_material_id');
        $productNo = request('product_no');
        $sellerCompanyIds = request('seller_id');
        $customerId = request('customer_id');
        $imgId = request('img_id',0);
        $warningNumber = request('warning_number',0);
        $fullNumber = request('full_number',0);

        $tmpAssemblageMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$assemblageMaterialId])->first();
        if(!$tmpAssemblageMaterialRow){
            return [
                'code' => 1,
                'message' => '参数错误',
            ];
        }

        //支持一次性添加多个供应商
        $sellerCompanyIdArr = explode(',',$sellerCompanyIds);
        foreach ($sellerCompanyIdArr as $key => $val){
            if(!$val){
                unset($sellerCompanyIdArr[$key]);
            }
        }

        if(empty($sellerCompanyIdArr)){
            return [
                'code' => 1,
                'message' => '请选择供应商',
            ];
        }

        $existSellerCompanyTitleList = [];
        foreach ($sellerCompanyIdArr as $sellerCompanyId){
            //同一个材料集合下，如果所有权人，供应商一致限制提交
            $existCount = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$assemblageMaterialId,'seller_company_id'=>$sellerCompanyId,'customer_id'=>$customerId])->count();
            if($existCount){
                //获取供应商名称
                $sellerCompanyTitle = '';
                $tmpObj = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$sellerCompanyId])->first();
                if($tmpObj){
                    $sellerCompanyTitle = $tmpObj->title ? $tmpObj->title : '';
                }
                $existSellerCompanyTitleList[] = $sellerCompanyTitle;

            }
        }

        if(!empty($existSellerCompanyTitleList)){
            $showStr = implode(',',$existSellerCompanyTitleList);
            return [
                'code' => 1,
                'message' => "供应商{$showStr}已存在",
            ];
        }



        foreach ($sellerCompanyIdArr as $sellerCompanyId){
            if(!$sellerCompanyId){//过滤空
                continue;
            }

            //限制相同编号
            $productNo = EngineProduct::createProductNo();
            $existCount = \App\Eloquent\Ygt\Product::where(['product_no'=>$productNo])->count();
            if($existCount){
                return [
                    'code' => 1,
                    'message' => '材料编号已存在',
                ];
            }

            $proudctInsertRow = $tmpAssemblageMaterialRow->toArray();
            unset($proudctInsertRow['created_at']);
            unset($proudctInsertRow['updated_at']);

            $proudctInsertRow['number'] = 0;//新增材料库存为0
            $proudctInsertRow['assemblage_material_id'] = $assemblageMaterialId;
            $proudctInsertRow['product_no'] = $productNo;
            $proudctInsertRow['seller_company_id'] = $sellerCompanyId;
            $proudctInsertRow['customer_id'] = $customerId;
            $proudctInsertRow['img_id'] = $imgId;
            $proudctInsertRow['warning_number'] = $warningNumber;
            $proudctInsertRow['full_number'] = $fullNumber;

            $tmpObj = \App\Eloquent\Ygt\Product::firstOrNew(['id'=>'']);
            $tmpObj->fill($proudctInsertRow);
            $tmpObj->save();


//            //如果供应商的主营材料里没有该材料，自动添加（主要用于全显示供应商后的情况）
//            $tmpObj = \App\Eloquent\Ygt\SellerCompanyMaterial::firstOrNew(['seller_company_id'=>$sellerCompanyId,'assemblage_material_id'=>$assemblageMaterialId]);
//            $tmpObj->seller_company_id = $sellerCompanyId;
//            $tmpObj->assemblage_material_id = $assemblageMaterialId;
//            $tmpObj->save();
        }

        return [
            'code' => 0,
            'message' => '操作成功'
        ];
    }

    public function getAssemblageMaterialInfo()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $productId          = request('product_id',0);
        if(!$userInfo || !$productId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $product            = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$productId])->first();
        if(!$product)
        {
            xThrow(ERR_UNKNOWN,'材料信息出错');
        }
        $info               = $product->toArray();
//        $imagePath          = \App\Engine\Func::getImgUrlHttp($info['img_id']);
        $imagePath          =  \App\Eloquent\Ygt\ImgUpload::getImgUrlById($info['img_id']);;
        $info['img_path']   = $imagePath;



        //追加材料分类名称
        $categoryName = '';
        $tmpCategoryRow = \App\Eloquent\Ygt\Category::where(['id'=>$info['category_id']])->first();
        if($tmpCategoryRow){
            $categoryName = $tmpCategoryRow->cat_name;
        }

        $info['category_name']   = $categoryName;

        //获取当前用户权限
        $privilegeAppnode   = \App\Eloquent\Ygt\Privilege::getAppnodeList( $userInfo['privilege_id'] )->toArray();
        $privilegeAppnodeIdList = [];
        foreach ($privilegeAppnode as $privilegeAppnodeRow){
            $privilegeAppnodeIdList[] = $privilegeAppnodeRow['id'];
        }

        //厂长、下单人或者仓管员权限可以删除材料
        $isAbleDelete = 0;
        if(in_array(1,$privilegeAppnodeIdList) || in_array(9,$privilegeAppnodeIdList) || in_array(7,$privilegeAppnodeIdList)){
            $isAbleDelete =1;
        }

        $info['is_able_delete'] = $isAbleDelete;

        return $info;
    }

    //修改材料,只允许修改部分属性
    public function editAssemblageMaterial()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $productId          = request('id',0);
        $productName        = request('product_name','');
        $categoryId         = request('category_id',0);
        $imgId              = request('img_id',0);
        $isCustomer         = request('is_customer',1);
        $customerId         = request('customer_id',0);
        $customerId         = intval($customerId);
        if(!$userInfo || !$productId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $requestData        = request()->all();
        $where              = ['company_id'=>$companyId,'id'=>$productId];

        $product            = \App\Eloquent\Ygt\AssemblageMaterial::where($where)->first();
        if(!$product)
        {
            xThrow(ERR_UNKNOWN,'材料信息出错');
        }
        $productData        = [
            'product_name'=>$productName,
            'category_id'=>$categoryId,
            'img_id'=>$imgId,
        ];

        $product->fill($productData);
        $product->save();

        //2019-01-23 Linwei 材料集合的图片更新不更新sku的图片
        $skuProductData  = [
            'product_name'=>$productName,
            'category_id'=>$categoryId
        ];
        //修改sku材料信息
        $productList = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$productId])->get();
        foreach($productList as $tmpProductRow){
            $tmpProductRow->fill($skuProductData);
            $tmpProductRow->save();
        }
        return ['message'=>'修改成功'];
    }


    public function deleteAssemblageMaterial(){
        $params = request()->only('product_id','product_no');

        $re = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$params['product_id']])->first()->delete();

        if($re){
            return 'ok';
        }else{
            xThrow(ERR_PRODUCT_DELETE_FAIL);
        }
    }


    //退品材料-列表
    public function getMaterialRetreatList(){
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $userInfo['company_id'];

        $limit              = request('limit',10);
        $page               = request('page',1);

        $offset             = ($page-1)*$limit;

        $keyword                = request('keyword','');

        $where = ['company_id'=>$companyId];
        if(!empty($keyword)){
            $idArr = Product::where('product_name','like',"%".$keyword."%")->get()->pluck('id');
            $where['material_id'] = ['in',$idArr];
        }

        //获取材料列表信息
        $where = [];
        $where[] = ['company_id','=',$companyId];
        $where[] = ['material_id','!=',0];
        $materialRetreatList = \App\Eloquent\Ygt\MaterialRetreat::where($where)->skip($offset)->take($limit)->get();
        $count = \App\Eloquent\Ygt\MaterialRetreat::where($where)->count();

        if(!empty($materialRetreatList)){
            $materialRetreatList = $materialRetreatList->toArray();
        }else{
            $materialRetreatList = [];
        }

        //补充材料信息
        foreach ($materialRetreatList as $key => $materialRetreatRow){
            $tmpMaterialId = $materialRetreatRow['material_id'];
            //获取材料处理过的信息，属性值，库存，比例等
            $tmpMaterialRow = \App\Engine\Material::getMaterialDealInfo($tmpMaterialId);
            if(!$tmpMaterialRow){
                //过滤异常数据
                unset($materialRetreatList[$key]);
                continue;
            }
            $tmpMaterialRow = $tmpMaterialRow->toArray();

            //过滤数据
            unset($tmpMaterialRow['id']);
            unset($tmpMaterialRow['number']);
            unset($tmpMaterialRow['radio']);

            //新加数据
            $radion = 0;
            if($materialRetreatRow['number_all']){
                $radion = $materialRetreatRow['number'] / $materialRetreatRow['number_all'];
            }

            $materialRetreatList[$key] = array_merge($materialRetreatRow,$tmpMaterialRow);
        }

        $materialRetreatList = array_values($materialRetreatList);



        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
        ];
        return $this->pagingData($materialRetreatList, $pagingData);
    }

    //获取退品出入库流水
    public function getWaterList(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId          = $userInfo->company_id;
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $date          = request('date','');
        $page          = request('page',1);


        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $MaterialRetreatLogObj = new MaterialRetreatLog();
        if(!empty($date)){
            $startTime = strtotime($date);
            $endTime = $startTime+24*3600;

            $MaterialRetreatLogObj = $MaterialRetreatLogObj->whereBetween('ygt_material_retreat_log.created_at',[$startTime,$endTime]);
        }
        //2019-01-23 Linwei  增加本厂限制
        $MaterialRetreatLogObj->where("company_id","=",$companyId);
        //获得总数
        $count = $MaterialRetreatLogObj->count();

        //获得数据
        $lists = $MaterialRetreatLogObj->leftJoin('ygt_product','ygt_product.id','=','ygt_material_retreat_log.material_id')
            ->leftJoin('ygt_user','ygt_user.id','=','ygt_material_retreat_log.user_id')
            ->skip($offset)->take($limit)
            ->orderBy('created_at','desc')
            ->get([
                'ygt_material_retreat_log.id',
                'ygt_material_retreat_log.sn',
                'ygt_material_retreat_log.type',
                'ygt_material_retreat_log.number',
                'ygt_material_retreat_log.created_at',
                'ygt_product.product_name as name',
                'ygt_user.truename as operate_name'
            ])
            ->toArray();

        //修改时间显示格式
        foreach ($lists as $key => $tmpRow){
            $lists[$key]['created_time'] = date('Y-m-d H:i:s',$tmpRow['created_at']);
            $lists[$key]['residual_number'] = '';

            if($tmpRow['type'] == 1){
                $lists[$key]["type_name" ] = "工单退品入库";
                $lists[$key]["type_color" ] = "#04C9B3";
            }elseif($tmpRow['type'] == 2){
                $lists[$key]["type_name" ] = "退品出库";
                $lists[$key]["type_color" ] = "#04C9B3";
            }
            else{
                $lists[$key]["type_name" ] = "未知类型";
                $lists[$key]["type_color" ] = "#04C9B3";
            }


        }

        $listData           = [
            'list'=>$lists,
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }

    //退品材料-详情
    public function getMaterialRetreatDetail(){

        $relateType = request('relate_type');//相关类型
        $materialRetreatId              = request('material_retreat_id');//废品材料ID
        $relateId = request('relate_id');//工序工单ID

        if($relateType && $relateType == 1 && $relateId){
            $materialId = $materialRetreatId;//这个时候material_retreat_id作为材料ID了，将错就错

            if(strstr($materialId,'A')){
                //集合材料取集合材料下的第一个sku材料
                $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                $materialRow = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->first();
                $materialId = $materialRow['id'];
            }

            //获取对应材料退品ID
            //通过工序工单ID获取对应的材料提交记录ID
            $orderProcessMaterialSubmitIdArr = \App\Eloquent\Ygt\OrderProcessMaterialSubmit::where(['order_process_id'=>$relateId])->get()->pluck('id');
            $tmpMaterialRetreatLog = \App\Eloquent\Ygt\MaterialRetreatLog::where(['material_id'=>$materialId])->whereIn('relate_id',$orderProcessMaterialSubmitIdArr)->first();
            $materialRetreatId = $tmpMaterialRetreatLog['material_retreat_id'];
        }

        $materialRetreatRow = \App\Eloquent\Ygt\MaterialRetreat::where(['id'=>$materialRetreatId])->first();

        if(!empty($materialRetreatRow)){
            $materialRetreatRow = $materialRetreatRow->toArray();
        }else{
            return [
                'code' => 1,
                'message' => '无数据'
            ];
        }

        $tmpMaterialId = $materialRetreatRow['material_id'];
        $tmpMaterialRow = \App\Engine\Material::getMaterialDealInfo($tmpMaterialId);

        if(!empty($tmpMaterialRow)){
            $tmpMaterialRow = $tmpMaterialRow->toArray();
        }else{
            $tmpMaterialRow = [];
        }

        //过滤数据
        unset($tmpMaterialRow['id']);
        unset($tmpMaterialRow['number']);
        unset($tmpMaterialRow['radio']);

        $materialRetreatRow = array_merge($materialRetreatRow,$tmpMaterialRow);

        $materialRetreatRow['number_in'] = $materialRetreatRow['number_all'];
        $materialRetreatRow['number_out'] = $materialRetreatRow['number_all'] - $materialRetreatRow['number'];


        $limit              = request('limit',10);
        $page               = request('page',1);
        $offset             = ($page-1)*$limit;
        //获取流水记录

        $where = ['material_retreat_id'=>$materialRetreatId];
        if($relateType && $relateId){
            $where['relate_id'] = $relateId;
            $where['type'] = $relateType;
        }

        $materialRetreatLogList = \App\Eloquent\Ygt\MaterialRetreatLog::where($where)->skip($offset)->take($limit)->get();
        $count = \App\Eloquent\Ygt\MaterialRetreatLog::where($where)->count();

        $logList = [];
        foreach ($materialRetreatLogList as $materialRetreatLogRow){

            $createdAt = ($materialRetreatLogRow->toArray())['created_at'];
            $createdTime = date('Y-m-d H:i:s',$createdAt);

            //获取操作员名称
            $trueName = '';
            $tmpDepartmentUserRow = \App\Eloquent\Ygt\DepartmentUser::where(['user_id'=>$materialRetreatLogRow['user_id']])->first();
            if($tmpDepartmentUserRow){
                $trueName = $tmpDepartmentUserRow['truename'];
            }

            //数据处理
            $tmpArr = [
                "id"            =>$materialRetreatLogRow['id'],
                "water_no"      =>$materialRetreatLogRow['id'],
                "product_id"    =>$materialRetreatLogRow['material_id'],
                "number"        =>$materialRetreatLogRow['number'],
                "type"          =>$materialRetreatLogRow['type'],
                "relate_type"   => '',
                "last_product_number"  => '',
                "operate_uid"   => $materialRetreatLogRow['user_id'],
                "relate_id"     => $materialRetreatLogRow['relate_id'],
                "created_at"    => $createdAt,
                "place_name"    => "",
                "product_name"  => "",
                "product_no"    => "",
                "operate_name"  => $trueName,
//                "relate_type_title" => "工单废品入库",
//                "relate_type_color" => "#04C9B3",
                "created_time"      => $createdTime
            ];

            if($materialRetreatLogRow['type'] == 1){
                $tmpArr["relate_type_title" ] = "工单退品入库";
                $tmpArr["relate_type_color" ] = "#04C9B3";
            }elseif($materialRetreatLogRow['type'] == 2){
                $tmpArr["relate_type_title" ] = "退品出库";
                $tmpArr["relate_type_color" ] = "#04C9B3";
            }

            $logList[] = $tmpArr;
        }

        $listData       = [
            'print_button'=>'',
            'info'=>$materialRetreatRow,
            'list'=>$logList,
        ];
        $pagingData     = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }

    //获取分类下所有集合材料信息
    public function getAssemblageMaterialListByCategoryId(){
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId              = $userInfo->company_id;
        //传参
        $categoryIdStr          = request('category_id',0);//多个逗号隔开
        $keyword                = request('keyword','');

        $where['ygt_assemblage_material.company_id']    = $companyId;


        if ($categoryIdStr)
        {
            $categoryIdArr      = explode(',', $categoryIdStr);
            foreach($categoryIdArr as $v)
            {
                if(!$v){//过滤空
                    continue;
                }

                $categoryModel  = new Category();
                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                $category       = collect($categoryArr);
                $tempCategoryIds = $category->map(function ($c) {
                    return $c['id'];
                })->toArray();
                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
            }
            $categoryIdArr      = array_unique($categoryIdArr);
            $where['category_id']   = ['in',$categoryIdArr];
        }

        if($keyword != '')
        {
            $where['product_name']   = ['like', '%'.$keyword.'%'];
        }

        $productList        = \App\Eloquent\Ygt\AssemblageMaterial::getList($where,'id,product_name')->toArray();

        return $productList;
    }


    //获取全选的材料ID
    public function getAssemblageMaterialIdList(){
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId              = $userInfo->company_id;
        //传参
        $categoryIdStr          = request('category_id',0);//多个逗号隔开!!!!!!!!!莫名其妙
        $isPublic               = request('is_public','');
        $warningNumber          = request('warning_number',0);
        $keyword                = request('keyword','');
        $sellerCompanyId                = request('seller_company_id','');
        ////////////////////////////////////////////////////
        /// 之下的字段不会同时出现!!!!!!
        /// 不用type和type_id来区分是因为app的需求

//        $params                 = request()->only('category_id', 'product_name', 'product_no','page');
//        $rules                  = [];
//        $this->validateRequestParameters($params, $rules);

        $where                  = [];
        $where['ygt_assemblage_material.company_id']    = $companyId;
        //新增通过供应商的主营业务过滤 zhuyujun 20181113
        if($sellerCompanyId){
            $assemblageMaterialIdArr = \App\Eloquent\Ygt\SellerCompanyMaterial::where(['seller_company_id'=>$sellerCompanyId])->get()->pluck('assemblage_material_id');
            $where['ygt_assemblage_material.id']   = ['in',$assemblageMaterialIdArr];
        }


        if ($categoryIdStr)
        {
            $categoryIdArr      = explode(',', $categoryIdStr);
            foreach($categoryIdArr as $v)
            {
                if(!$v){//过滤空
                    continue;
                }

                $categoryModel  = new Category();
                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                $category       = collect($categoryArr);
                $tempCategoryIds = $category->map(function ($c) {
                    return $c['id'];
                })->toArray();
                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
            }
            $categoryIdArr      = array_unique($categoryIdArr);
            $where['ygt_assemblage_material.category_id']   = ['in',$categoryIdArr];
        }
        if ($warningNumber)
        {
            $where[]            = ['whereRaw','number <= warning_number'];
        }
        if (in_array($isPublic,['yes','no']))
        {
            $where['ygt_assemblage_material.is_public']     = $isPublic;
        }
        if($keyword!='')
        {
            $where['ygt_assemblage_material.product_name']   = ['like', '%'.$keyword.'%'];
        }

        //取列表
        $productIdList        = \App\Eloquent\Ygt\AssemblageMaterial::getListByJoinAssemblageMaterial($where,'','')->pluck('id');

        return [
            'id_list' => $productIdList,
        ];
    }

    //批量添加供应商材料
    public function batchCreateSupplierMaterial(){
        $sellerCompanyId = request('seller_company_id','');
        $assemblageMaterialIdListStr = request('assemblage_material_id_list');
        $customerId = request('customer_id',0);

        if(empty($sellerCompanyId)){
            return [
                'code' => 1,
                'message' => '请选择供应商',
            ];
        }

        $assemblageMaterialIdList = explode(',',$assemblageMaterialIdListStr);
        if(empty($assemblageMaterialIdList)){
            return [
                'code' => 1,
                'message' => '请选择材料',
            ];
        }

        foreach ($assemblageMaterialIdList as $assemblageMaterialId){
            if(!$assemblageMaterialId){//过滤空
                continue;
            }

            $tmpAssemblageMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$assemblageMaterialId])->first();
            if(!$tmpAssemblageMaterialRow){
                continue;//过滤异常
            }

            //过滤已经存在的材料
            $tmpRow = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$assemblageMaterialId,'seller_company_id'=>$sellerCompanyId,'customer_id'=>$customerId])->first();
            if($tmpRow){
                continue;
            }


            //限制相同编号
            $productNo = EngineProduct::createProductNo();

            $proudctInsertRow = $tmpAssemblageMaterialRow->toArray();
            unset($proudctInsertRow['created_at']);
            unset($proudctInsertRow['updated_at']);

            $proudctInsertRow['number'] = 0;//新增材料库存为0
            $proudctInsertRow['assemblage_material_id'] = $assemblageMaterialId;
            $proudctInsertRow['product_no'] = $productNo;
            $proudctInsertRow['seller_company_id'] = $sellerCompanyId;
            $proudctInsertRow['customer_id'] = $customerId;

            $tmpObj = \App\Eloquent\Ygt\Product::firstOrNew(['id'=>'']);
            $tmpObj->fill($proudctInsertRow);
            $tmpObj->save();
        }

        return [
            'code' => 0,
            'message' => '操作成功'
        ];


    }

}












